package com.emellend.api.view;



import com.emellend.api.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/**
 * 自定义控件
 * @author emellend
 *
 */
public class LabelView extends View {

	private Paint mTextPaint;
	private String mText;
	private int mAscent;
	
	public LabelView(Context context) {
		super(context);
		initLabelView();
	}

	public LabelView(Context context,AttributeSet attrs) {
		super(context, attrs);
		initLabelView();
		
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LabelView);
		CharSequence s=a.getText(R.styleable.LabelView_text).toString();
		if (s!=null) {
			setText(s.toString());
		}
		setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000));
		int textSize=a.getDimensionPixelOffset(R.styleable.LabelView_textSize, 0);
		if (textSize>0) {
			setTextSize(textSize);
		}
		a.recycle();
	}
	

	private void setTextSize(int textSize) {
		mTextPaint.setTextSize(textSize);
		requestLayout();
		invalidate();
	}

	private void setTextColor(int color) {
		mTextPaint.setColor(color);
		invalidate();
	}

	private void setText(String string) {
		mText=string;
		requestLayout();
		invalidate();
	}

	private void initLabelView() {
		mTextPaint = new Paint();
		mTextPaint.setAntiAlias(true);
		mTextPaint.setTextSize(16);
		mTextPaint.setColor(0xFF000000);
		setPadding(3, 3, 3, 3);
	}
	/**
	 * 调用measure(int,int)时触发
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
	}
	
	private int measureWidth(int measureSpec) {
		int result=0;
		int specMode=MeasureSpec.getMode(measureSpec);
		int specSize=MeasureSpec.getSize(measureSpec);
		if (specMode==MeasureSpec.EXACTLY) {
			result=specSize;
		}else {
			result=(int) (mTextPaint.measureText(mText)+getPaddingLeft()+getPaddingRight());
			if (specMode==MeasureSpec.AT_MOST) {
				result=Math.min(result, specSize);
			}
		}
		return result;
	}
	
	private int measureHeight(int measureSpec){
		int result=0;
		int specMode=MeasureSpec.getMode(measureSpec);
		int specSize=MeasureSpec.getSize(measureSpec);
		mAscent = (int) mTextPaint.ascent();
		if (specMode==MeasureSpec.EXACTLY) {
			result=specSize;
		}else {
			result=(int) (-mAscent+mTextPaint.descent()+getPaddingTop()+getPaddingBottom());
			if (specMode==MeasureSpec.AT_MOST) {
				result=Math.min(result, specSize);
			}
		}
		return result;
	}
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.drawText(mText, getPaddingLeft(), getPaddingTop()-mAscent, mTextPaint);
	}
}
